package com.xuzhiguang.lightnat.client.common.handler;

import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.common.KeepAliveRequest;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class KeepAliveHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == IdleStateEvent.FIRST_ALL_IDLE_STATE_EVENT) {
            KeepAliveRequest body = new KeepAliveRequest();
            body.setTime(System.currentTimeMillis());
            NatMessage natMessage = new NatMessage(body);

            ctx.channel().writeAndFlush(natMessage);
        }

        super.userEventTriggered(ctx, evt);
    }
}
